/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY. 
 * See the GNU General Public License for more details.
 * 
 * Copyright (C) 2011 CellObject.net
 */
package net.cellobject.javacodeformatter;

import net.cellobject.javacodeformatter.log.FormatterLog;
import net.cellobject.javacodeformatter.view.FormatterView;

import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;


public class FormatterPluginStartup implements IStartup{

	@Override
	public void earlyStartup() {		
		IWorkbenchPage page = null;
		IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
		if (window != null){
			page = window.getActivePage();
		}

		if (page == null){
			// Look for a window and get the page off it!
			IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
			for (int i = 0; i < windows.length; i++){
				if (windows[i] != null){
					window = windows[i];
					page = windows[i].getActivePage();
					if (page != null){
						break;
					}
				}
			}
		 }
	   
	      //Open and activate the Formatter view.
	      try {	    	 
	    	 final IWorkbenchPage activePage = page;
	    	 Display.getDefault().syncExec( new Runnable() {
	    		    public void run(){
	    		    	 try {
	    		    		 activePage.showView(FormatterView.ID);
						} catch (Exception e) {							
							e.printStackTrace();
						}
	    		    }
	    		  });
	      }
	      catch (Exception e) {	    	 
	         FormatterLog.logError("Failed to open the Formatter view", e);
	      }	     
		
	}
	
	
}
